package cn.hsa.xxx.inStorage.service.impl;

import cn.hsa.xxx.bookData.bo.BookInventoryBO;
import cn.hsa.xxx.bookData.bo.InventoryBatchBO;
import cn.hsa.xxx.api.dto.BookInventoryDTO;
import cn.hsa.xxx.api.dto.InventoryBatchDTO;
import cn.hsa.xxx.inStorage.service.InStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class InStorageServiceImpl implements InStorageService {

    @Autowired
    private BookInventoryBO bookInventoryBO;

    @Autowired
    private InventoryBatchBO inventoryBatchBO;

    @Override
    @Transactional//开启事务处理
    public BookInventoryDTO addStorage(InventoryBatchDTO inventoryBatchDTO) {

        //获取inventoryBatchDTO中属性
        String inventoryBatchUuid = inventoryBatchDTO.getInventoryBatchUuid();
        String bookUuid = inventoryBatchDTO.getBookUuid();
        Integer quantity = inventoryBatchDTO.getQuantity();
        /*Date createTime = inventoryBatchDTO.getCreateTime();*/
        Date updateTime = inventoryBatchDTO.getUpdateTime();

        //库存批次处理
        inventoryBatchBO.add(inventoryBatchDTO);

        //库存数据处理
        BookInventoryDTO bookInventoryDTO = bookInventoryBO.getByBookUuid(bookUuid);
        if(bookInventoryDTO == null) {
            //插入新的库存数据
            bookInventoryDTO = new BookInventoryDTO(
                    inventoryBatchUuid, bookUuid, quantity, quantity, updateTime, updateTime, updateTime);
            bookInventoryBO.add(bookInventoryDTO);
        }
        else {
            //在原来的库存数据上累加
            Integer inventoryQuantity = bookInventoryDTO.getInventoryQuantity();
            Integer inventoryRemaining = bookInventoryDTO.getInventoryRemaining();
            bookInventoryDTO.setInventoryQuantity(inventoryQuantity+quantity);
            bookInventoryDTO.setInventoryRemaining(inventoryRemaining+quantity);
            bookInventoryDTO.setInventoryQuantityUpdateTime(updateTime);
            bookInventoryDTO.setUpdateTime(updateTime);
            bookInventoryBO.update(bookInventoryDTO);
        }

        return bookInventoryDTO;
    }
}
